using DailyPoetryH.Server.Commands;
using DailyPoetryH.Server.Services;
using Microsoft.AspNetCore.Mvc;
using TheSalLab.GeneralReturnValues;

namespace DailyPoetryH.Server.Controllers;

[ApiController]
[Route("[controller]")]
public class HomeController {
    private readonly IPoetryComposingService _poetryComposingService;

    public HomeController(IPoetryComposingService poetryComposingService) {
        _poetryComposingService = poetryComposingService;
    }

    [Route("poetrilize")]
    [HttpPost]
    public async Task<ServiceResultViewModel<string>> PoetrilizeAsync(
        [FromForm] PoetrilizationCommand command) {
        using var httpClient = new HttpClient();
        using var formData = new MultipartFormDataContent {
            {new StreamContent(command.File.OpenReadStream()), "file", "file"}
        };

        HttpResponseMessage response;
        try {
            response = await httpClient.PostAsync(
                "http://dailypoetryh.server.image2text:8000/", formData);
            response.EnsureSuccessStatusCode();
        } catch (Exception e) {
            return ServiceResult<string>.CreateExceptionResult(e, e.Message)
                .ToServiceResultViewModel();
        }

        var topic = await response.Content.ReadAsStringAsync();
        var result = await _poetryComposingService.ComposeAsync(topic);

        return result.ToServiceResultViewModel();
    }
}